//
//  HNHappyFamilyMusicWorldController.m
//  XDEducation
//
//  Created by 星道 on 17/6/5.
//  Copyright © 2017年 apple. All rights reserved.
//

#import "HNHappyFamilyMusicWorldController.h"
#import "HNHappyFamilyMusicWorldModel.h"
#import "HNHappyFamilyMusicWorldCell.h"
#import "HNAudioPlayer.h"
#import "HNDownLoadFile.h"
#import "HNDownLoadMusicWorld.h"

@interface HNHappyFamilyMusicWorldController ()
@property (nonatomic, strong) NSMutableArray *DataArr;
@property (nonatomic, assign) NSInteger Index;
@property (nonatomic, strong) HNHappyFamilyMusicWorldModel *TempPlayerModel;
@end

@implementation HNHappyFamilyMusicWorldController

/** 界面即将消失时移除播放 */
- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [HNAudioPlayer Close];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    self.title = @"音乐世界";
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"已下载" style:(UIBarButtonItemStyleDone) target:self action:@selector(GoDownLoadButton:)];
    
    self.Index = 1;
    
    //统计点击量
    [self CountClicks];
    
    self.tableView.tableHeaderView = [UIView new];
    self.tableView.tableFooterView = [UIView new];
    
    [self.tableView registerNib:[UINib nibWithNibName:[HNHappyFamilyMusicWorldCell description] bundle:nil] forCellReuseIdentifier:@"Cell"];
    
    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        [self RefreshData];
    }];
    [self.tableView.mj_footer beginRefreshing];
}

#pragma mark - 网络请求
/** 网络请求 */
- (void)RefreshData
{
    NSDictionary *Dict = @{
                           @"action":@"musiclist",
                           @"page"  :@(self.Index)
                           };
    [XDHttpTool get:BaseURL(@"media.do") authCode:[AccountTool shareAccountTool].currentAccount.authCode params:Dict success:^(id responseObj) {
        [self.tableView.mj_footer endRefreshing];
        if (responseObj)
        {
            if ([responseObj[@"dataList"] count] == 0)
            {
                [self.tableView.mj_footer endRefreshingWithNoMoreData];
            }
            else
            {
                for (NSDictionary *Dict in responseObj[@"dataList"])
                {
                    HNHappyFamilyMusicWorldModel *Model = [HNHappyFamilyMusicWorldModel mj_objectWithKeyValues:Dict];
                    
                    Model.IsReal = [HNDownLoadFile JudgePathIsRealWithFileName:[NSString stringWithFormat:@"%@.%@",Model.musicTitle,[Model.absoluteUrl pathExtension]]];
                    [self.DataArr addObject:Model];
                }
                self.Index += 1;
                [self.tableView reloadData];
            }
        }
        else
        {
            [MBProgressHUD showError:responseObj[@"msg"]];
        }
    } failure:^(NSError *error) {
        [self.tableView.mj_footer endRefreshing];
        [MBProgressHUD showError:XDNetWorkError];
    }];
}




#pragma mark - TableView代理
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.DataArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    HNHappyFamilyMusicWorldCell *Cell = [tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath:indexPath];
    HNHappyFamilyMusicWorldModel *MusicModel = self.DataArr[indexPath.row];;
    Cell.Model = MusicModel;
    //操控
    Cell.ClickPlayer = ^(HNHappyFamilyMusicWorldModel *TempPlayerModel, BOOL IsSelfModel)
    {
        //按钮状态
        if (!IsSelfModel)
        {
            self.TempPlayerModel.IsPlay = !self.TempPlayerModel.IsPlay;
            self.TempPlayerModel = TempPlayerModel;
            [self.tableView reloadData];
        }
    };
    //下载
    Cell.ClickDownLoad = ^(HNHappyFamilyMusicWorldModel *Model)
    {
        [HNDownLoadFile DownFileWithModel:Model Progress:^(CGFloat Index) {
            //进度显示
            MusicModel.Progress = Index;
            
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:(UITableViewRowAnimationNone)];
                
            });
        } Complete:^(NSString *FullPath, NSError *Err) {
            
            if (Err)
            {
                //下载失败
                //删除记录
                [MBProgressHUD showError:@"下载失败"];
                [HNDownLoadFile RemovePathForCheckPath:FullPath];
                MusicModel.Progress = 0;
                dispatch_async(dispatch_get_main_queue(), ^{
                    [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:(UITableViewRowAnimationNone)];
                    
                });
            }
            else
            {
                //下载完成
                Model.IsReal = YES;
                dispatch_async(dispatch_get_main_queue(), ^{
                    [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:(UITableViewRowAnimationNone)];
                    
                });
            }
        }];
    };
    return Cell;
}





#pragma mark - Func
/** 前往已下载 */
- (void)GoDownLoadButton:(UIBarButtonItem *)Button
{
    HNDownLoadMusicWorld *VC = [[HNDownLoadMusicWorld alloc] init];
    [self.navigationController pushViewController:VC animated:YES];
}






#pragma mark - Setter
- (NSMutableArray *)DataArr
{
    if (!_DataArr)
    {
        _DataArr = [NSMutableArray array];
    }
    return _DataArr;
}


#pragma mark - PS:统计点击量
- (void)CountClicks
{
    NSDictionary *Dict = @{
                           @"uid"       :[AccountTool shareAccountTool].currentAccount.uid,
                           @"funcCode"  :@3,
                           @"action"    :@"countClicks"
                           };
    [XDHttpTool get:BaseURL(@"user.do") authCode:[AccountTool shareAccountTool].currentAccount.authCode params:Dict success:^(id responseObj) {
    } failure:^(NSError *error) {
    }];
}
@end
